package com.icesoft.core.web.helper;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import com.icesoft.core.common.exception.CheckException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class ValidatorHelp {

	/**
	 * 校验model里的数据是否通过验证
	 * 
	 * @throws CheckException
	 *             未通过验证的字段信息
	 * @param object
	 *            要验证的对象
	 * @param includes
	 *            要校验的字段，为空表示对所有字段进行校验
	 */
	public static <T> void validate(T object, String... includes) throws CheckException {
		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		Set<ConstraintViolation<T>> set = vf.getValidator().validate(object);
		if (set.isEmpty()) {
			return;
		}
		StringBuilder message = new StringBuilder();
		StringBuilder LogMessage = new StringBuilder();
		List<String> list = Arrays.asList(includes);
		for (ConstraintViolation<T> constraintViolation : set) {
			String fieldName = constraintViolation.getPropertyPath().toString();
			if (!list.isEmpty() && !list.contains(fieldName)) {
				continue;
			}
			message.append("[").append(constraintViolation.getMessage()).append("：")
					.append(constraintViolation.getInvalidValue()).append("] ");
			LogMessage.append("[").append(constraintViolation.getMessage()).append("，").append(fieldName).append("：")
					.append(constraintViolation.getInvalidValue()).append("] ");
		}
		log.info("{}数据验证失败：{}", object.getClass().getSimpleName(), LogMessage.toString());
		throw new CheckException(message.toString());
	}

	/**
	 * 校验model里的数据是否通过验证
	 * 
	 * @param object
	 *            要验证的对象
	 * @param includes
	 *            要校验的字段，为空表示对所有字段进行校验
	 * @return 是否通过验证
	 */
	public static <T> boolean isValidate(T object, String... includes) {
		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		Set<ConstraintViolation<T>> set = vf.getValidator().validate(object);
		if (set.isEmpty()) {
			return true;
		}
		if (includes.length == 0) {
			return false;
		}

		List<String> list = Arrays.asList(includes);
		for (ConstraintViolation<T> constraintViolation : set) {
			String fieldName = constraintViolation.getPropertyPath().toString();
			if (list.contains(fieldName)) {
				return false;
			}
		}
		return true;
	}
}
